import { Effect, Reducer } from 'umi';
import { list, deleteUser } from './service';

export interface UserMgrStateType {
  isLoading: boolean;
  isAdd: boolean;
  currentIndex: number;
}

export interface UserMgrModelType {
  namespace: string;
  state: UserMgrStateType;
  effects: {
    list: Effect;
    delUserInfo: Effect;
  };
  reducers: {
    setResult: Reducer;
    saveListResult: Reducer;
  };
}

const userMgrModel: UserMgrModelType = {
  namespace: 'userMgr',
  state: {
    isLoading: false,
    isAdd: false,
    currentIndex: -1,
  },
  effects: {
    *list({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({
        type: 'saveListResult',
        payload: response,
      });
    },
    *delUserInfo({ payload }, { call, put }) {
      const response = yield call(deleteUser, payload);
      if (response.state === 'ok') {
        const listResponse = yield call(list);
        yield put({
          type: 'saveListResult',
          payload: listResponse,
        });
      }
    },
  },
  reducers: {
    setResult(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    saveListResult(state, { payload }) {
      return {
        ...state,
        list: payload.data,
      };
    },
  },
};

export default userMgrModel;
